package com.android.gl2jni.filter;

import android.opengl.GLES20;

import android.content.Context;

/**
 * Create time: 2018/9/26.
 */
public class ShakeFilterProgram extends TextureFilterProgram {
  int mTextureCoordOffsetLoc;
  private float mProgress = 0.0f;

  private int mFrames = 0;

  private static final int mMaxFrames = 8;

  private static final int mSkipFrames = 4;

  private static final String FRAGMENT =
      "#extension GL_OES_EGL_image_external : require\n"
          + "precision mediump float;\n"
          + "uniform samplerExternalOES uTexture;\n"
          + "varying vec2 vTextureCoord;\n"
          + "uniform float uTextureCoordOffset;\n"
          + "\n"
          + "void main(){\n"
          + "    vec4 blue = texture2D(uTexture,vTextureCoord);\n"
          + "    vec4 green = texture2D(uTexture,vec2(vTextureCoord.x + uTextureCoordOffset,vTextureCoord.y + uTextureCoordOffset));\n"
          + "    vec4 red = texture2D(uTexture,vec2(vTextureCoord.x - uTextureCoordOffset,vTextureCoord.y - uTextureCoordOffset));\n"
          + "    gl_FragColor = vec4(red.x,green.y,blue.z,blue.w);\n"
          + "}";

  public ShakeFilterProgram(Context context) {
    super(context, ProgramType.TEXTURE_EXT);
  }

  @Override
  protected void initProgram() {
    super.initProgram();
    mTextureCoordOffsetLoc = getUniformLocation("uTextureCoordOffset");
  }

  @Override
  protected void onDraw(int firstVertex, int vertexCount) {
    mProgress = (float) mFrames / mMaxFrames;
    if (mProgress > 1f) {
      mProgress = 0f;
    }
    mFrames++;
    if (mFrames > mMaxFrames + mSkipFrames) {
      mFrames = 0;
    }
    float textureCoordOffset = 0.01f * mProgress;
    setFloat(mTextureCoordOffsetLoc, textureCoordOffset);
    super.onDraw(firstVertex, vertexCount);
  }

  @Override
  protected String getFragmentShaderSourceEXT() {
    return FRAGMENT;
  }
}
